import {
  Controller,
  Res,
  HttpStatus,
  Body,
  Post,
  BadRequestException,
} from '@nestjs/common';
import { ExcelService } from './excel.service';
import { ExcelDto } from './dto/excel.dto';
import { ApiBody, ApiTags, ApiResponse, ApiOperation } from '@nestjs/swagger';

@Controller('export')
@ApiTags('公共Excel导出')
export class ExcelController {
  constructor(private readonly excelService: ExcelService) {}

  @Post('/exportExcel')
  @ApiOperation({
    summary: 'excel导出',
    description: 'excel导出',
  })
  @ApiBody({ type: ExcelDto })
  @ApiResponse({ status: 200, description: '导出成功' })
  exportExcel(@Body() body: ExcelDto, @Res() res) {
    try {
      // 导出为 Excel 文件
      const buffer = this.excelService.exportAsExcelFile(body.data);

      // 设置响应头
      res.setHeader(
        'Content-Type',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      );
      res.setHeader(
        'Content-Disposition',
        `attachment; filename=${encodeURIComponent(body.filename)}`,
      );

      // 发送文件
      res.status(HttpStatus.OK).send(buffer);
    } catch {
      throw new BadRequestException('Excel公共导出接口调用失败');
    }
  }
}
